//
//  ATJgAdsSplashAdapter.m
//  eseecloud
//
//  Created by Yc on 2022/10/17.
//  Copyright © 2022 juanvision. All rights reserved.
//

#import "JgAdsSplashAdapter.h"
#import "JgAdsSplashCustomEvent.h"


#import "ATJgAdsBiddingRequest.h"
#import "ATJgAdsBiddingManager.h"

#import "JgAdsSplashAdContainer.h"

@interface JgAdsSplashAdapter ()
@property (nonatomic, strong) JgAdsSplashCustomEvent *customEvent;
@property (nonatomic, strong) JgAdsSplashAdContainer *splashAdContainer;
@end

@implementation JgAdsSplashAdapter

-(instancetype) initWithNetworkCustomInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo {
    self = [super init];
    if (self != nil) {
        [JgAdsSDK initWithAppId:serverInfo[@"app_id"] completionBlock:^(NSError * _Nullable error) {
            if (error){
                NSLog(@"JgAdsSDK 初始化失败%@",error);
            }
        }];
    }
    return self;
}

- (void)loadADWithInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo completion:(void (^)(NSArray<NSDictionary *> *, NSError *))completion {
    
    NSTimeInterval tolerateTimeout = localInfo[kATSplashExtraTolerateTimeoutKey] ? [localInfo[kATSplashExtraTolerateTimeoutKey] doubleValue] : 5.0;
    if (tolerateTimeout > 0) {
        _customEvent = [[JgAdsSplashCustomEvent alloc] initWithInfo:serverInfo localInfo:localInfo];
        _customEvent.requestCompletionBlock = completion;
//        _customEvent.delegate = self.delegateToBePassed;
        
       
        NSString *bidId = serverInfo[kATAdapterCustomInfoBuyeruIdKey];
        if (bidId.length) {
            
            ATJgAdsBiddingRequest *request = [[ATJgAdsBiddingManager sharedInstance] getRequestItemWithUnitID:serverInfo[@"slot_id"]];
            
            if (request.customObject!=nil) { // load secced
                self.splashAdContainer = request.customObject;
                self.splashAdContainer.delegate = _customEvent;
                _customEvent.splashAdContainer = self.splashAdContainer;
                [_customEvent trackSplashAdLoaded:self.splashAdContainer];
            } else { // fail
//                NSError *error = [NSError errorWithDomain:ATADLoadingErrorDomain code:ATADLoadingErrorCodeThirdPartySDKNotImportedProperly userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load splash.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}];
                [_customEvent trackSplashAdLoadFailed:nil];
            }
            [[ATJgAdsBiddingManager sharedInstance] removeRequestItmeWithUnitID:serverInfo[@"slot_id"]];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->_customEvent loadAndShowPosId:serverInfo[@"slot_id"] window:[UIApplication sharedApplication].keyWindow withBottomView:nil];
            });
        }
    } else {
        completion(nil, [NSError errorWithDomain:ATADLoadingErrorDomain code:-1000001 userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load splash.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}]);
    }
}

//v 5.7.06 及以上版本中， splash 广告的 load 和 show 方法已经分开了
+ (void)showSplash:(ATSplash *)splash localInfo:(NSDictionary*)localInfo delegate:(id<ATSplashDelegate>)delegate {
    JgAdsSplashAdContainer *splashAdContainer = splash.customObject;
    if (splashAdContainer) {
        UIWindow *window = localInfo[kATSplashExtraWindowKey];
        [splashAdContainer showAdInWindow:window withBottomView:nil];
    }
}

+(BOOL)adReadyWithCustomObject:(id)customObject info:(NSDictionary*)info{
    JgAdsSplashAdContainer *splashAdContainer = customObject;
    return splashAdContainer?YES:NO;
}

#pragma mark - Header bidding
#pragma mark - c2s
+(void)bidRequestWithPlacementModel:(ATPlacementModel*)placementModel unitGroupModel:(ATUnitGroupModel*)unitGroupModel info:(NSDictionary*)info completion:(void(^)(ATBidInfo *bidInfo, NSError *error))completion {

    NSLog(@"%s", __FUNCTION__);
    if (NSClassFromString(@"JgAdsSDK") == nil) {
        if (completion != nil) { completion( nil, [NSError errorWithDomain:@"com.ubix.mediation.ios" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Bid request has failed", NSLocalizedFailureReasonErrorKey:@"JgAdsSDK is not imported"}]); }
        return;
    }
    [JgAdsSDK initWithAppId:info[@"app_id"] completionBlock:^(NSError * _Nullable error) {
        if (error){
            NSLog(@"JgAdsSDK 初始化失败%@",error);
        } else {
            
            ATJgAdsBiddingManager *biddingManage = [ATJgAdsBiddingManager sharedInstance];
            ATJgAdsBiddingRequest *request = [ATJgAdsBiddingRequest new];
            request.unitGroup = unitGroupModel;
            request.placementID = placementModel.placementID;
            request.bidCompletion = completion;
            request.unitID = info[@"slot_id"];
            request.extraInfo = info;
            request.adType = ESCAdFormatSplash;
            JgAdsSplashAdContainer *splashAdContainer = [[JgAdsSplashAdContainer alloc] initPosId:info[@"slot_id"] delegate:nil];
            request.customObject = splashAdContainer;
            [biddingManage startWithRequestItem:request];
            [splashAdContainer loadAdWithBottomView:nil];
            
        }
    }];
}

+ (void) sendWinnerNotifyWithCustomObject:(id)customObject secondPrice:(NSString*)price userInfo:(NSDictionary<NSString *, NSString *> *)userInfo {
    NSLog(@"%s", __FUNCTION__);    
    JgAdsSplashAdContainer *splashAdContainer = (JgAdsSplashAdContainer *)customObject;
    [splashAdContainer sendWinNotificationWithPrice:[splashAdContainer getBidPrice]];
    
#if DEBUG
    NSLog(@"JgAdsSDK=============开屏-上报竞赢价格：%ld",[splashAdContainer getBidPrice]);
#endif
}

+ (void)sendLossNotifyWithCustomObject:(nonnull id)customObject lossType:(ATBiddingLossType)lossType winPrice:(nonnull NSString *)price userInfo:(NSDictionary *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    //美元转人民币，转换为分
    CGFloat cnyPrice = price.floatValue * 6.3 * 100;
    JgAdsSplashAdContainer *splashAdContainer = (JgAdsSplashAdContainer *)customObject;
    JgAdsBiddingLossReason reason = JgAdsBiddingLossReasonOther;
    if (lossType == ATBiddingLossWithLowPriceInNormal || lossType == ATBiddingLossWithLowPriceInHB) {
        reason = JgAdsBiddingLossReasonLowPrice;
    }
    [splashAdContainer sendWinFailNotificationReason:reason winnerPirce:@(cnyPrice).integerValue];
    
#if DEBUG
    NSLog(@"JgAds=============开屏-上报竞败；竞败原因：%ld竞赢价格：%ld",(long)reason,@(cnyPrice).integerValue);
#endif
}

/*
 说明：
 将JgAdsSDK 以自定义适配器方式接入topon
 平台已经配置了适配器和广告位。
 1.当广告位没有开启头部竞价功能，ESCAdmobileSplashAdapter 会走初始化方法-(instancetype) initWithNetworkCustomInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo
 和 - (void)loadADWithInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo completion:(void (^)(NSArray<NSDictionary *> *, NSError *))completion 加载广告，三方广告回调也能正常加载展示。
 2.将topon 广告源开启head bidding 功能后 适配器触发+(void)bidRequestWithPlacementModel:(ATPlacementModel*)placementModel unitGroupModel:(ATUnitGroupModel*)unitGroupModel info:(NSDictionary*)info completion:(void(^)(ATBidInfo *bidInfo, NSError *error))completion 方法。上面初始化和加载广告的就不走了。
 
3.自定义适配器的 head bidding 逻辑按文档描述大致对接如上，广告加载触发不了。因文档介绍不详，麻烦看下还有哪些需要补充的逻辑
 
 */

@end
